<template>
  <div class="book-list">
    <div class="page-header">
      <h2>图书列表</h2>
      <el-button type="primary" @click="handleAdd">添加图书</el-button>
    </div>

    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="书名">
          <el-input v-model="searchForm.name" placeholder="请输入书名" clearable />
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="searchForm.author" placeholder="请输入作者" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-table :data="bookList" border style="width: 100%" v-loading="loading">
      <el-table-column prop="name" label="书名" />
      <el-table-column prop="author" label="作者" />
      <el-table-column prop="publisher" label="出版社" />
      <el-table-column prop="isbn" label="ISBN" />
      <el-table-column prop="totalCount" label="总数量" width="100" />
      <el-table-column prop="availableCount" label="可借数量" width="100" />
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button 
            type="success" 
            link 
            @click="handleBorrow(row)" 
            :disabled="row.availableCount === 0"
          >
            借出
          </el-button>
          <el-button
            type="warning"
            link
            @click="handleReturn(row)"
            :disabled="row.availableCount >= row.totalCount"
          >
            归还
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="pagination"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="total"
      :page-sizes="[10, 20, 50]"
      layout="total, sizes, prev, pager, next"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        style="max-width: 460px"
      >
        <el-form-item label="书名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" />
        </el-form-item>
        <el-form-item label="出版社" prop="publisher">
          <el-input v-model="form.publisher" />
        </el-form-item>
        <el-form-item label="ISBN" prop="isbn">
          <el-input v-model="form.isbn" />
        </el-form-item>
        <el-form-item label="总数量" prop="totalCount">
          <el-input-number v-model="form.totalCount" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog
      title="借阅图书"
      v-model="borrowDialogVisible"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="borrowFormRef"
        :model="borrowForm"
        :rules="borrowRules"
        label-width="80px"
      >
        <el-form-item label="借阅人" prop="borrower">
          <el-input v-model="borrowForm.borrower" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="borrowForm.contact" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="borrowDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBorrowSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

// 列表数据
const bookList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  name: '',
  author: ''
})

// 弹窗表单
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const form = reactive({
  id: null,
  name: '',
  author: '',
  publisher: '',
  isbn: '',
  totalCount: 0
})

const rules = {
  name: [{ required: true, message: '请输入书名', trigger: 'blur' }],
  author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
  publisher: [{ required: true, message: '请输入出版社', trigger: 'blur' }],
  isbn: [{ required: true, message: '请输入ISBN', trigger: 'blur' }],
  totalCount: [{ required: true, message: '请输入总数量', trigger: 'blur' }]
}

// 借阅表单
const borrowDialogVisible = ref(false)
const borrowFormRef = ref()
const borrowForm = reactive({
  bookId: null,
  borrower: '',
  contact: ''
})

const borrowRules = {
  borrower: [{ required: true, message: '请输入借阅人', trigger: 'blur' }],
  contact: [{ required: true, message: '请输入联系方式', trigger: 'blur' }]
}

// 获取图书列表
const getBookList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...searchForm
    }
    const res = await axios.get('/api/books', { params })
    bookList.value = res.data.records || res.data
    total.value = res.data.total || res.data.length
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('获取图书列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getBookList()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.author = ''
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getBookList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getBookList()
}

// 添加图书
const handleAdd = () => {
  dialogTitle.value = '添加图书'
  form.id = null
  form.name = ''
  form.author = ''
  form.publisher = ''
  form.isbn = ''
  form.totalCount = 0
  dialogVisible.value = true
}

// 编辑图书
const handleEdit = (row) => {
  dialogTitle.value = '编辑图书'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 删除图书
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该图书吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await axios.delete(`/api/books/${row.id}`)
      ElMessage.success('删除成功')
      getBookList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id) {
          await axios.put(`/api/books/${form.id}`, form)
        } else {
          await axios.post('/api/books', form)
        }
        ElMessage.success(form.id ? '编辑成功' : '添加成功')
        dialogVisible.value = false
        getBookList()
      } catch (error) {
        ElMessage.error(form.id ? '编辑失败' : '添加失败')
      }
    }
  })
}

// 借出图书
const handleBorrow = (row) => {
  borrowForm.bookId = row.id
  borrowForm.borrower = ''
  borrowForm.contact = ''
  borrowDialogVisible.value = true
}

// 归还图书
const handleReturn = async (row) => {
  try {
    await ElMessageBox.confirm('确定要归还这本书吗？', '提示', {
      type: 'warning'
    })
    await axios.put(`/api/borrows/${row.id}/return`)
    ElMessage.success('归还成功')
    getBookList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Error:', error)
      ElMessage.error('归还失败')
    }
  }
}

// 提交借阅
const handleBorrowSubmit = async () => {
  if (!borrowFormRef.value) return
  await borrowFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await axios.post('/api/borrows', {
          bookId: borrowForm.bookId,
          borrower: borrowForm.borrower,
          contact: borrowForm.contact,
          status: 'BORROWED'
        })
        ElMessage.success('借出成功')
        borrowDialogVisible.value = false
        getBookList()
      } catch (error) {
        console.error('Error:', error)
        ElMessage.error('借出失败')
      }
    }
  })
}

onMounted(() => {
  getBookList()
})
</script>

<style scoped>
.book-list {
  min-height: 100%;
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
